﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web;
using Microsoft.SharePoint.Utilities;
using System.Data;
using Microsoft.SharePoint.Administration;
using zevenseas.LifeCycleManagement.Utilities;
using Microsoft.SharePoint;
using System.Reflection;

namespace zevenseas.LifeCycleManagement.ApplicationPages
{
    public class OverviewWebs : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected SPGridView gridView;
        protected TextBox TxtUrlSearch;
        protected DVDropDownList ColumnDropDown;
        protected DVDropDownList SortDropDown;
        protected DVDropDownList SortDirectionDropDown;
        protected WebApplicationSelector webApplicationSelector;

        private ObjectDataSource dataSource;
        private DataView dataView;
        private string folderNameWebApp;

        public OverviewWebs()
        {
            folderNameWebApp  = "Unused " + this.Context.Request.QueryString["WebAppId"].ToString() + " - Webs";
        }

        protected override void CreateChildControls()
        {
            //BindData(); 
            gridView.ID = "gridView";
            gridView.AutoGenerateColumns = false;

            gridView.AlternatingRowStyle.BackColor = System.Drawing.Color.WhiteSmoke;

            // Create the datasource object
            dataSource = new ObjectDataSource();

            string strTypeName = "zevenseas.LifeCycleManagement.ApplicationPages.OverviewWebs,";
            strTypeName += Assembly.GetExecutingAssembly().FullName;

            dataSource.TypeName = strTypeName;
            dataSource.SelectMethod = "GetWebs";
            dataSource.ID = "MyDataSource";

            dataView = (DataView)dataSource.Select();

            HttpRequest oRequest = HttpContext.Current.Request;
            if ((oRequest.Form["__CALLBACKID"] == null) ||
                (oRequest.Form["__CALLBACKPARAM"] == null) ||
                (!oRequest.Form["__CALLBACKID"].EndsWith("gridView")))
            {

            }

            Controls.Add(dataSource);

            // Bind SPGridView to datasource object            
            gridView.DataSource = dataView;

            base.CreateChildControls();
        }



        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            BindData();
            base.Render(writer);
        }

        public void ViewLink(object sender, EventArgs e)
        {
        }

        public void SearchLinkClick(object sender, EventArgs e)
        {
            BindData();
        }

        public void BackLink(object sender, EventArgs e)
        {
            SPUtility.Redirect("/_admin/lcm/overviewsites.aspx", SPRedirectFlags.Default, this.Context, "WebApplicationId=" + this.Context.Request.QueryString["WebAppId"].ToString());
        }

        public void BindData()
        {
            dataView = (DataView)dataSource.Select();
            string statusFilter = string.Empty;

            if (dataView != null)
            {
                if (TxtUrlSearch != null)
                {
                    if (!string.IsNullOrEmpty(TxtUrlSearch.Text.ToString()))
                    {
                        statusFilter = ColumnDropDown.SelectedValue + " LIKE '*" + TxtUrlSearch.Text + "*'";
                        dataView.RowFilter = statusFilter;
                    }
                }

                if (SortDropDown != null)
                {
                    dataView.Sort = SortDropDown.SelectedValue.ToString() + " " + SortDirectionDropDown.SelectedValue.ToString();
                }
            }

            gridView.DataSource = dataView;
            gridView.DataBind();
        }

        public DataView GetWebs()
        {
            DataView dataView = null;

            string siteGuid = this.Context.Request.QueryString["SiteId"].ToString();
           // string folderNameWebApp = "Unused " + this.Context.Request.QueryString["WebAppId"].ToString() + " - Webs";

            if (!string.IsNullOrEmpty(siteGuid))
            {               
                SPWebApplication webApplication = SPAdministrationWebApplication.Local;                

                if (Utilities.Utilities.DoesWebExist(webApplication) && Utilities.Utilities.DoesListExist(this.Site.OpenWeb("LCM"), folderNameWebApp))
                {
                    SPWeb lcmWeb = this.Site.OpenWeb("LCM");
                    folderNameWebApp = folderNameWebApp.Replace("-", "");
                    SPFolder folder = lcmWeb.GetFolder("/LCM/Lists/" + folderNameWebApp + "/" + siteGuid);

                    string sortExpression = string.Empty;
                    string newDirection = string.Empty;

                    SPQuery query = new SPQuery();
                    query.Query = "<OrderBy><FieldRef Name='Size' Ascending=’" + newDirection + "’/></OrderBy>";
                    query.Folder = folder;

                    DataTable websTable = lcmWeb.Lists[folder.ParentListId].GetItems(query).GetDataTable();

                    if (websTable != null)
                    {
                        dataView = new DataView(websTable);
                    }
                }
            }

            return dataView;
        }

        private string[] RetrieveIDs()
        {
            string[] webs = null;
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                webs = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });
            }
            return webs;
        }

        public void MailLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        SPWebApplication webApplication = webApplicationSelector.CurrentItem;
                        SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);                                                

                        SiteLifeCycleSettings settings = webApplication.GetChild<SiteLifeCycleSettings>("SiteLifeCycleSettings");

                        string emailBody = string.Empty;
                        string emailSubject = string.Empty;

                        if (settings != null)
                        {
                            emailBody = settings.emailBody.ToString();
                            emailSubject = settings.emailSubject.ToString();
                        }

                        string emailTo = item["OwnerEmailAddress"].ToString();
                        ////string emailSubject = item["Title"] + " at : " + url + Utilities.Utilities.GetWebProperty("mailSubject", SPContext.Current.Web.Properties);
                        ////string emailBody = Utilities.Utilities.GetWebProperty("mailContent", SPContext.Current.Web.Properties);

                        if (SPUtility.SendEmail(item.ParentList.ParentWeb, false, false, emailTo, emailSubject, emailBody))
                        {
                            //updating list if email is successfully sent
                            item["MailedAt"] = System.DateTime.Today;
                            item["Mailed"] = true;
                            item.Update();
                        }
                    }
                }
            }
        }

        public void DeleteLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {                        
                        SPListItem item = Utilities.Utilities.GetAssociatedListItem(url, folderNameWebApp);

                        bool siteIsDeleted = false;

                        try
                        {
                            
                            using (SPSite site = new SPSite(new Guid(item["SiteGuid"].ToString())))
                            {
                                using (SPWeb web = site.OpenWeb(new Guid(item["WebGuid"].ToString())))
                                {
                                    if (!web.IsRootWeb)
                                    {
                                        web.Delete();                                    
                                    }

                                    else
                                    {
                                        site.Delete();                                    
                                    }

                                    siteIsDeleted = true;
                                }
                            }
                        }

                        catch (Exception error)
                        {
                            SPUtility.TransferToErrorPage(error.Message.ToString());
                        }

                        if (siteIsDeleted)
                        {                            
                            item["Deleted"] = true;
                            item["DeletedAt"] = System.DateTime.Today;
                            item.Update();

                        }
                    }
                }
            }
        }

        public void SiteSettingsLink(object sender, EventArgs e)
        {
            Guid siteGuid = new Guid(this.Context.Request.QueryString["SiteId"].ToString());
            Guid webAppGuid = new Guid(webApplicationSelector.CurrentId);
            string returnUrl = string.Empty;

            string[] webs = RetrieveIDs();
            if (webs != null)
            {
                foreach (string web in webs)
                {
                    if (!string.IsNullOrEmpty(web))
                    {                        
                        SPListItem item = Utilities.Utilities.GetAssociatedListItem(web, folderNameWebApp);
                        Guid webId = new Guid(item["WebGuid"].ToString());

                        SPWebApplication webApplication = SPWebService.ContentService.WebApplications[webAppGuid];
                        using (SPSite site = new SPSite(siteGuid))
                        {
                            using (SPWeb destWeb = site.AllWebs[webId])
                            {
                                returnUrl = destWeb.Url + "/_layouts/settings.aspx";
                            }
                        }
                        break;
                    }
                }
            }

            this.Page.Response.Redirect(returnUrl);
        }

        public void MinorVersionsLink(object sender, EventArgs e)
        {
            DeleteAction(Delete.Minor);
        }

        public void VersionsLink(object sender, EventArgs e)
        {
            DeleteAction(Delete.All);
        }

        private void DeleteAction(Delete deleteAction)
        {
            Guid siteGuid = new Guid(this.Context.Request.QueryString["SiteId"].ToString());
            Guid webAppGuid = new Guid(this.Context.Request.QueryString["WebAppId"].ToString());
            string returnUrl = string.Empty;

            string[] webs = RetrieveIDs();
            if (webs != null)
            {
                foreach (string web in webs)
                {
                    if (!string.IsNullOrEmpty(web))
                    {
                        Guid webId = new Guid(web);
                        SPWebApplication webApplication = SPWebService.ContentService.WebApplications[webAppGuid];
                        using (SPSite site = new SPSite(siteGuid))
                        {
                            using (SPWeb destWeb = site.AllWebs[webId])
                            {
                                foreach (SPFolder folder in destWeb.Folders)
                                {
                                    DeleteVersions(folder, deleteAction);
                                }
                            }
                        }
                    }
                }
            }
        }

        private void DeleteVersions(SPFolder folder, Delete deleteAction)
        {
            foreach (SPFile file in folder.Files)
            {
                switch (deleteAction)
                {
                    case Delete.All:
                        file.Versions.DeleteAll();
                        break;
                    case Delete.Minor:
                        file.Versions.DeleteAllMinorVersions();
                        break;
                }

            }

            foreach (SPFolder subFolder in folder.SubFolders)
            {
                DeleteVersions(subFolder, deleteAction);
            }

        }

        public enum Delete
        {
            Minor,
            All

        }
    }
}
